<template>
  <div class="website-config">
    <div class="config-grid">
      <!-- 个人信息卡片 -->
      <a-card class="config-card" title="个人信息配置">
        <template #extra>
          <icon-user />
        </template>
        <a-form :model="formData" layout="vertical">
          <a-form-item field="profileBackground" label="个人卡片背景图">
            <div class="upload-wrapper">
              <a-upload
                list-type="picture-card"
                :file-list="profileBgFileList"
                :limit="1"
                :custom-request="customUpload"
                @change="handleProfileBgChange"
              >
                <template #upload-button>
                  <div class="upload-button">
                    <icon-plus />
                    <div class="upload-text">上传图片</div>
                  </div>
                </template>
              </a-upload>
            </div>
          </a-form-item>
          <a-form-item field="profileAvatar" label="个人头像">
            <div class="upload-wrapper">
              <a-upload
                list-type="picture-card"
                :file-list="avatarFileList"
                :limit="1"
                :custom-request="customUpload"
                @change="handleAvatarChange"
              >
                <template #upload-button>
                  <div class="upload-button">
                    <icon-plus />
                    <div class="upload-text">上传头像</div>
                  </div>
                </template>
              </a-upload>
            </div>
          </a-form-item>
        </a-form>
      </a-card>

      <!-- 首页配置卡片 -->
      <a-card class="config-card" title="首页配置">
        <template #extra>
          <icon-home />
        </template>
        <a-form :model="formData" layout="vertical">
          <a-form-item field="homeTitle" label="首页标题">
            <a-input
              v-model="formData.homeTitle"
              placeholder="请输入首页标题"
              allow-clear
            />
          </a-form-item>
          <a-form-item field="homeSubtitle" label="首页副标题">
            <a-input
              v-model="formData.homeSubtitle"
              placeholder="请输入首页副标题"
              allow-clear
            />
          </a-form-item>
          <a-form-item field="homeCarouselImages" label="首页轮播图">
            <div class="upload-wrapper">
              <a-upload
                list-type="picture-card"
                :file-list="homeCarouselFileList"
                multiple
                :custom-request="customUpload"
                @change="handleHomeCarouselChange"
              >
                <template #upload-button>
                  <div class="upload-button">
                    <icon-plus />
                    <div class="upload-text">上传图片</div>
                  </div>
                </template>
              </a-upload>
            </div>
          </a-form-item>
        </a-form>
      </a-card>
      <!-- 归档页面配置 -->
      <a-card class="config-card" title="归档页面配置">
        <template #extra>
          <icon-calendar />
        </template>
        <a-form :model="formData" layout="vertical">
          <a-form-item field="archiveTitle" label="归档页面标题">
            <a-input
              v-model="formData.archiveTitle"
              placeholder="请输入归档页面标题"
              allow-clear
            />
          </a-form-item>
          <a-form-item field="archiveSubtitle" label="归档页面副标题">
            <a-input
              v-model="formData.archiveSubtitle"
              placeholder="请输入归档页面副标题"
              allow-clear
            />
          </a-form-item>
          <a-form-item field="archiveCarouselImages" label="归档页面轮播图">
            <div class="upload-wrapper">
              <a-upload
                list-type="picture-card"
                :file-list="carouselFileLists.archive"
                multiple
                :custom-request="customUpload"
                @change="(info: any) => handleCarouselChange(info, 'archive')"
              >
                <template #upload-button>
                  <div class="upload-button">
                    <icon-plus />
                    <div class="upload-text">上传图片</div>
                  </div>
                </template>
              </a-upload>
            </div>
          </a-form-item>
        </a-form>
      </a-card>

      <!-- 文章页面配置 -->
      <a-card class="config-card" title="文章页面配置">
        <template #extra>
          <icon-file />
        </template>
        <a-form :model="formData" layout="vertical">
          <a-form-item field="articleTitle" label="文章页面标题">
            <a-input
              v-model="formData.articleTitle"
              placeholder="请输入文章页面标题"
              allow-clear
            />
          </a-form-item>
          <a-form-item field="articleSubtitle" label="文章页面副标题">
            <a-input
              v-model="formData.articleSubtitle"
              placeholder="请输入文章页面副标题"
              allow-clear
            />
          </a-form-item>
          <a-form-item field="articleCarouselImages" label="文章页面轮播图">
            <div class="upload-wrapper">
              <a-upload
                list-type="picture-card"
                :file-list="carouselFileLists.article"
                multiple
                :custom-request="customUpload"
                @change="(info: any) => handleCarouselChange(info, 'article')"
              >
                <template #upload-button>
                  <div class="upload-button">
                    <icon-plus />
                    <div class="upload-text">上传图片</div>
                  </div>
                </template>
              </a-upload>
            </div>
          </a-form-item>
        </a-form>
      </a-card>

      <!-- 时间线配置 -->
      <a-card class="config-card" title="时间线配置">
        <template #extra>
          <icon-clock-circle />
        </template>
        <a-form :model="formData" layout="vertical">
          <a-form-item field="timelineTitle" label="时间线页面标题">
            <a-input
              v-model="formData.timelineTitle"
              placeholder="请输入时间线页面标题"
              allow-clear
            />
          </a-form-item>
          <a-form-item field="timelineSubtitle" label="时间线页面副标题">
            <a-input
              v-model="formData.timelineSubtitle"
              placeholder="请输入时间线页面副标题"
              allow-clear
            />
          </a-form-item>
          <a-form-item field="timelineCarouselImages" label="时间线页面轮播图">
            <div class="upload-wrapper">
              <a-upload
                list-type="picture-card"
                :file-list="carouselFileLists.timeline"
                multiple
                :custom-request="customUpload"
                @change="(info: any) => handleCarouselChange(info, 'timeline')"
              >
                <template #upload-button>
                  <div class="upload-button">
                    <icon-plus />
                    <div class="upload-text">上传图片</div>
                  </div>
                </template>
              </a-upload>
            </div>
          </a-form-item>
        </a-form>
      </a-card>

      <!-- 更新日志配置 -->
      <a-card class="config-card" title="更新日志配置">
        <template #extra>
          <icon-history />
        </template>
        <a-form :model="formData" layout="vertical">
          <a-form-item field="changelogTitle" label="更新日志页面标题">
            <a-input
              v-model="formData.changelogTitle"
              placeholder="请输入更新日志页面标题"
              allow-clear
            />
          </a-form-item>
          <a-form-item field="changelogSubtitle" label="更新日志页面副标题">
            <a-input
              v-model="formData.changelogSubtitle"
              placeholder="请输入更新日志页面副标题"
              allow-clear
            />
          </a-form-item>
          <a-form-item
            field="changelogCarouselImages"
            label="更新日志页面轮播图"
          >
            <div class="upload-wrapper">
              <a-upload
                list-type="picture-card"
                :file-list="carouselFileLists.changelog"
                multiple
                :custom-request="customUpload"
                @change="(info: any) => handleCarouselChange(info, 'changelog')"
              >
                <template #upload-button>
                  <div class="upload-button">
                    <icon-plus />
                    <div class="upload-text">上传图片</div>
                  </div>
                </template>
              </a-upload>
            </div>
          </a-form-item>
        </a-form>
      </a-card>

      <!-- 分类配置 -->
      <a-card class="config-card" title="分类配置">
        <template #extra>
          <icon-history />
        </template>
        <a-form :model="formData" layout="vertical">
          <a-form-item field="categoryTitle" label="分类页面标题">
            <a-input
              v-model="formData.categoryTitle"
              placeholder="请输入分类页面标题"
              allow-clear
            />
          </a-form-item>
          <a-form-item field="categorySubtitle" label="分类页面副标题">
            <a-input
              v-model="formData.categorySubtitle"
              placeholder="请输入分类页面副标题"
              allow-clear
            />
          </a-form-item>
          <a-form-item field="categoryCarouselImages" label="分类页面轮播图">
            <div class="upload-wrapper">
              <a-upload
                list-type="picture-card"
                :file-list="carouselFileLists.category"
                multiple
                :custom-request="customUpload"
                @change="(info: any) => handleCarouselChange(info, 'category')"
              >
                <template #upload-button>
                  <div class="upload-button">
                    <icon-plus />
                    <div class="upload-text">上传图片</div>
                  </div>
                </template>
              </a-upload>
            </div>
          </a-form-item>
        </a-form>
      </a-card>
    </div>

    <div class="actions">
      <a-space size="large">
        <a-button size="large" @click="resetForm">
          <template #icon>
            <icon-refresh />
          </template>
          重置
        </a-button>
        <a-button
          type="primary"
          size="large"
          :loading="loading"
          @click="submitForm"
        >
          <template #icon>
            <icon-save />
          </template>
          保存配置
        </a-button>
      </a-space>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';
  import { Message, RequestOption } from '@arco-design/web-vue';
  import type { FileItem as UploadItem } from '@arco-design/web-vue';
  import type { UploadRequest } from '@arco-design/web-vue/es/upload/interfaces';
  import {
    IconUser,
    IconHome,
    IconCalendar,
    IconFile,
    IconClockCircle,
    IconHistory,
    IconPlus,
    IconRefresh,
    IconSave,
  } from '@arco-design/web-vue/es/icon';
  import { selectWebConfig, saveWebConfig } from '@/api/webconfig';
  import { uploadFile } from '@/api/file';

  // 加载状态
  const loading = ref(false);

  // 表单数据
  const formData = reactive({
    profileBackground: '',
    profileAvatar: '',
    homeTitle: '',
    homeSubtitle: '',
    homeCarouselImages: '',
    archiveTitle: '',
    archiveSubtitle: '',
    archiveCarouselImages: '',
    articleTitle: '',
    articleSubtitle: '',
    articleCarouselImages: '',
    timelineTitle: '',
    timelineSubtitle: '',
    timelineCarouselImages: '',
    changelogTitle: '',
    changelogSubtitle: '',
    changelogCarouselImages: '',
    categoryTitle: '',
    categorySubtitle: '',
    categoryCarouselImages: '',
  });

  // 文件列表
  const profileBgFileList = ref<UploadItem[]>([]);
  const avatarFileList = ref<UploadItem[]>([]);
  const homeCarouselFileList = ref<UploadItem[]>([]);
  const carouselFileLists = reactive({
    archive: [] as UploadItem[],
    article: [] as UploadItem[],
    timeline: [] as UploadItem[],
    changelog: [] as UploadItem[],
    category: [] as UploadItem[],
  });

  // 自定义上传方法
  const customUpload = (async (option: RequestOption) => {
    const { onError, onSuccess, fileItem } = option;
    const allowImgType = [
      'image/jpeg',
      'image/png',
      'image/jpg',
      'image/webp',
    ].includes(fileItem.file?.type as string);
    const isLt5M = (fileItem.file?.size as number) / 1024 / 1024 < 5;
    if (!allowImgType) {
      Message.error('图片只能是 PNG/JPG/JPEG 格式!');
      return onError('error');
    }
    if (!isLt5M) {
      Message.error('图片大小不能超过 5MB!');
      return onError('error');
    }

    try {
      const uploadData = new FormData();
      uploadData.append('file', fileItem.file as File);
      uploadData.append('category', 'background');
      const result = await uploadFile(uploadData);
      onSuccess(result);
      return result;
    } catch (error) {
      onError(error);
      Message.error('上传失败');
      return error;
    }
  }) as unknown as (option: RequestOption) => UploadRequest;

  // 处理图片上传
  const handleProfileBgChange = (fileList: UploadItem[]) => {
    profileBgFileList.value = fileList;
    const lastFile = fileList[fileList.length - 1];
    if (lastFile?.response?.data?.src) {
      formData.profileBackground = lastFile.response.data.src;
    }
  };

  const handleAvatarChange = (fileList: UploadItem[]) => {
    avatarFileList.value = fileList;
    const lastFile = fileList[fileList.length - 1];
    if (lastFile?.response?.data?.src) {
      formData.profileAvatar = lastFile.response.data.src;
    }
  };

  const handleHomeCarouselChange = (fileList: UploadItem[]) => {
    homeCarouselFileList.value = fileList;

    // 获取现有的URLs
    let existingUrls: string[] = [];
    try {
      existingUrls = formData.homeCarouselImages
        ? JSON.parse(formData.homeCarouselImages)
        : [];
    } catch {
      existingUrls = [];
    }

    // 获取新上传文件的URLs
    const newUrls = fileList
      .filter((file) => file.response?.data?.src)
      .map((file) => file.response.data.src);

    // 合并现有URLs和新URLs，去重
    const allUrls = [...new Set([...existingUrls, ...newUrls])];

    // 如果文件被删除，从URLs中移除
    const currentFileNames = fileList.map((file) => {
      return file.response?.data?.src || file.url;
    });
    const finalUrls = allUrls.filter((url) => currentFileNames.includes(url));

    formData.homeCarouselImages = JSON.stringify(finalUrls);
  };

  const handleCarouselChange = (fileList: UploadItem[], pageKey: string) => {
    carouselFileLists[pageKey] = fileList;

    // 获取现有的URLs
    let existingUrls: string[] = [];
    try {
      existingUrls = formData[`${pageKey}CarouselImages`]
        ? JSON.parse(formData[`${pageKey}CarouselImages`])
        : [];
    } catch {
      existingUrls = [];
    }

    // 获取新上传文件的URLs
    const newUrls = fileList
      .filter((file) => file.response?.data?.src)
      .map((file) => file.response.data.src);

    // 合并现有URLs和新URLs，去重
    const allUrls = [...new Set([...existingUrls, ...newUrls])];

    // 如果文件被删除，从URLs中移除
    const currentFileNames = fileList.map((file) => {
      return file.response?.data?.src || file.url;
    });
    const finalUrls = allUrls.filter((url) => currentFileNames.includes(url));

    formData[`${pageKey}CarouselImages`] = JSON.stringify(finalUrls);
  };

  // 更新文件列表
  const updateCarousel = (key: string, images: string) => {
    if (!images) return [];
    try {
      const urls = JSON.parse(images);
      return urls.map((url: string, index: number) => ({
        uid: `${key}-${index}`,
        url,
        name: url.split('/').pop() || '',
      }));
    } catch {
      return [];
    }
  };

  const updateFileListsFromConfig = () => {
    if (formData.profileBackground) {
      profileBgFileList.value = [
        {
          uid: 'profile-bg-1',
          url: formData.profileBackground,
          name: formData.profileBackground.split('/').pop() || '',
        },
      ];
    }

    if (formData.profileAvatar) {
      avatarFileList.value = [
        {
          uid: 'profile-avatar-1',
          url: formData.profileAvatar,
          name: formData.profileAvatar.split('/').pop() || '',
        },
      ];
    }

    homeCarouselFileList.value = updateCarousel(
      'home',
      formData.homeCarouselImages,
    );
    carouselFileLists.archive = updateCarousel(
      'archive',
      formData.archiveCarouselImages,
    );
    carouselFileLists.article = updateCarousel(
      'article',
      formData.articleCarouselImages,
    );
    carouselFileLists.timeline = updateCarousel(
      'timeline',
      formData.timelineCarouselImages,
    );
    carouselFileLists.changelog = updateCarousel(
      'changelog',
      formData.changelogCarouselImages,
    );
    carouselFileLists.category = updateCarousel(
      'category',
      formData.categoryCarouselImages,
    );
  };

  // 获取配置数据
  const fetchConfig = async () => {
    try {
      loading.value = true;
      const res = await selectWebConfig();
      Object.assign(formData, res.data);
      updateFileListsFromConfig();
    } catch (error) {
      Message.error('获取配置失败');
    } finally {
      loading.value = false;
    }
  };

  // 提交表单
  const submitForm = async () => {
    try {
      loading.value = true;
      await saveWebConfig(formData);
      Message.success('配置保存成功');
    } catch (error) {
      Message.error('配置保存失败');
    } finally {
      loading.value = false;
    }
  };

  // 重置表单
  const resetForm = () => {
    fetchConfig();
  };

  // 页面加载时获取配置
  onMounted(() => {
    fetchConfig();
  });
</script>

<style scoped lang="less">
  .website-config {
    height: 100%;
    background-color: var(--color-bg-2);
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .config-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
    gap: 16px;
    overflow-y: auto;
    padding-right: 4px;
  }

  .config-card {
    background: var(--color-bg-1);
    border-radius: 4px;
    min-height: 380px;

    :deep(.arco-card-header) {
      border-bottom: 1px solid var(--color-border-2);
      padding: 16px 20px;

      .arco-card-title {
        font-size: 16px;
        font-weight: 500;
      }
    }

    :deep(.arco-card-body) {
      padding: 20px;
    }

    :deep(.arco-form-item) {
      margin-bottom: 24px;
    }
  }

  .upload-wrapper {
    height: 120px;
    overflow-y: auto;

    :deep(.arco-upload-list) {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-top: 8px;
    }

    :deep(.arco-upload-list-item),
    :deep(.arco-upload-trigger-picture-card) {
      width: 100px;
      height: 100px;
      margin: 0;
      border-radius: 4px;
      border: 1px dashed var(--color-border-2);
      transition: all 0.2s;
      flex-shrink: 0;

      &:hover {
        border-color: rgb(var(--primary-6));
      }
    }

    :deep(.arco-upload-list-item) {
      border-style: solid;

      &-picture {
        padding: 4px;
      }

      img {
        object-fit: cover;
        border-radius: 2px;
        width: 92px;
        height: 92px;
      }
    }

    &::-webkit-scrollbar {
      width: 4px;
      height: 4px;
    }

    &::-webkit-scrollbar-thumb {
      background: var(--color-text-4);
      border-radius: 2px;
    }

    &::-webkit-scrollbar-track {
      background: var(--color-fill-2);
      border-radius: 2px;
    }
  }

  .upload-button {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: var(--color-text-3);

    .upload-text {
      margin-top: 8px;
      font-size: 12px;
    }
  }

  .actions {
    display: flex;
    justify-content: center;
    padding: 16px 0 0 0;

    .arco-btn {
      padding: 0 24px;
      height: 40px;
    }
  }

  // 美化滚动条
  :deep(*::-webkit-scrollbar) {
    width: 6px;
    height: 6px;
  }

  :deep(*::-webkit-scrollbar-thumb) {
    background: var(--color-text-4);
    border-radius: 3px;
  }

  :deep(*::-webkit-scrollbar-track) {
    background: var(--color-fill-2);
    border-radius: 3px;
  }
</style>
